<?php
namespace app\api\Controller;
use Think\Controller;
use Think\Exception;

use app\admin\model\BookModel;
use app\admin\model\ArticleModel;
use app\admin\model\StudyModel;
use app\admin\model\MemberModel;

/**
 * @title 文章接口管理
 */
class Web extends \think\Controller{
    public static $pagenum = 3;
    private static $appid = WX_APPID;
    private static $secret = WX_SECRET;  

    /**
     * @title 获取文章列表
     * @desc  {"0":"接口地址：http://open.opqnext.com/index.php?c=article&a=index","1":"请求方式：GET","2":"接口备注：必须传入keys值用于通过加密验证"}
     * @param {"name":"page","type":"int","required":true,"default":"1","desc":"页数"}
     * @param {"name":"keys","type":"string","required":true,"default":"xxx","desc":"加密字符串,substr(md5(\"约定秘钥\".$page),8,16)"}
     * @param {"name":"word","type":"string","required":false,"default":"null","desc":"搜索关键字"}
     * @param {"name":"cate","type":"int","required":false,"default":0,"desc":"分类ID,不传表示所有分类"}
     * @param {"name":"size","type":"int","required":false,"default":5,"desc":"每页显示条数，默认为5"}
     
     * @return {"name":"status","type":"int","required":true,"desc":"返回码：1成功,0失败","level":1}
     * @return {"name":"message","type":"string","required":true,"desc":"返回信息","level":1}
     * @return {"name":"data","type":"array","required":true,"desc":"返回数据","level":1}
     * @return {"name":"id","type":"string","required":true,"desc":"文章ID(22位字符串)","level":2}
     * @return {"name":"title","type":"string","required":true,"desc":"文章标题","level":2}
     * @return {"name":"thumb","type":"string","required":true,"desc":"文章列表图","level":2}
     * @return {"name":"content","type":"text","required":true,"desc":"文章内容","level":2}
     * @return {"name":"cate","type":"int","required":true,"desc":"文章分类","level":2}
     * @return {"name":"tags","type":"array","required":true,"desc":"文章标签","level":2}
     * @return {"name":"id","type":"string","required":true,"desc":"标签ID","level":3}
     * @return {"name":"tag","type":"string","required":true,"desc":"标签名称","level":3}
     * @return {"name":"count","type":"int","required":true,"desc":"标签使用数","level":3}
     * @return {"name":"img","type":"array","required":true,"desc":"文章组图","level":2}
     */
    public function category(){
        $param = input('param.');
        $user_id = isset($_COOKIE['uid'])?$_COOKIE['uid']:'4';
        $limit = self::$pagenum;
        $pageNumber = isset($param['pageNumber'])?$param['pageNumber']:'1';
        $offset = ($pageNumber - 1) * $limit;
        $where = ['is_del' => '0','pid' => '0','is_put' => '1'];
        if(isset($param['pid'])){
            $where['pid'] = $param['pid'];
        }
        $category = new bookModel();
        $selectResult = $category->getbooksByWhere($where, $offset, $limit,'rank desc');
        foreach ($selectResult as $key => $value) {
            $selectResult[$key]['pic'] = APP_HTTP_HOST.$selectResult[$key]['pic'];
            $study = new StudyModel();
            $follow = $study->getAllstudys(['user_id' => $user_id,'book_id' => $value['id']]); 
            $selectResult[$key]['is_follow'] = $follow?'1':'0';
        }
        $return['total'] = $category->getAllbooks($where);  // 总数据
        $return['rows'] = $selectResult;
        return_function('200','',$return);
    }
    /*
    * 资讯
    */
    public function article(){
        $param = input('param.');
        $user_id = isset($_COOKIE['uid'])?$_COOKIE['uid']:'4';
        $limit = self::$pagenum;
        $pageNumber = isset($param['pageNumber'])?$param['pageNumber']:'1';
        $offset = ($pageNumber - 1) * $limit;
        $where = ['is_del' => '0'];
        if(isset($param['category_id'])){
            $where['book_son_id'] = $param['category_id'];
        }else{
            return_function('500','缺少类目参数');
        }
        $study = new StudyModel();
        $follow = $study->getAllstudys(['user_id' => $user_id,'book_id' => $param['category_id']]); 
        $article = new ArticleModel();
        $selectResult = $article->getArticlesByWhere($where, $offset, $limit,'rank desc');
        foreach ($selectResult as $key => $value) {
            $selectResult[$key]['pic'] = $selectResult[$key]['pic']?APP_HTTP_HOST.$selectResult[$key]['pic']:'';
            $selectResult[$key]['thumbnail'] = $selectResult[$key]['thumbnail']?$selectResult[$key]['thumbnail']:'';
            $selectResult[$key]['movie_path'] = $selectResult[$key]['movie_path']?APP_HTTP_HOST.$selectResult[$key]['movie_path']:'';
            $love = $study->getAllstudys(['user_id' => $user_id,'articles_id' => $value['id']]); 
            $selectResult[$key]['is_love'] = $love?'1':'0';
        }
        $return['total'] = $article->getAllArticles($where);  // 总数据
        $return['rows'] = $selectResult;
        $return['is_follow'] = $follow?'1':'0';
        return_function('200','',$return);
    }
    /*
    * 资讯内容
    */
    public function article_content(){
        $article_id = input('param.article_id');
        $user_id = isset($_COOKIE['uid'])?$_COOKIE['uid']:'4';
        $article = new ArticleModel();
        $article_data = $article->getOneArticle($article_id);
        if(empty($article_data)){
            return_function('500','没数据,非法操作');
        }
        return_function('200','',$article_data);
    }
    /*关注 / 喜欢*/
    public function follow_love(){
        $book_id = input('param.book_id');
        $article_id = input('param.article_id');
        if(!$book_id && !$article_id){
            return_function('404','参数缺失');
        }
        $user_id = isset($_COOKIE['uid'])?$_COOKIE['uid']:'4';
        $study = new StudyModel();
        if($book_id){
            $selectResult = $study->getOnestudy(['user_id' => $user_id,'book_id' => $book_id]);
            if($selectResult){
                $del = $study->deletestudy($selectResult['id']);
            }else{
                $data = [
                    'user_id' => $user_id,
                    'book_id' => $book_id,
                    'addtime' => NOW_TIME,
                ];
                $study = $study->addstudy($data);
            }
            return_function('200');
        }else{
            $selectResult = $study->getOnestudy(['user_id' => $user_id,'articles_id' => $article_id]);
            if($selectResult){
                $del = $study->deletestudy($selectResult['id']);
            }else{
                $data = [
                    'user_id' => $user_id,
                    'articles_id' => $article_id,
                    'addtime' => NOW_TIME,
                ];
                $study = $study->addstudy($data);
            }
            return_function('200');
        }
    
    }
    /*关注*/
    public function follow_list(){
        $user_id = isset($_COOKIE['uid'])?$_COOKIE['uid']:'4';
        $list = db('study')->alias('s')
           ->field('b.*')
           ->join('picture_book b','s.book_id = b.id')
           ->where("user_id = $user_id")
           ->select();
        return_function('200','',$list); 
    } 
    /*喜欢*/
    public function love_list(){
        $user_id = isset($_COOKIE['uid'])?$_COOKIE['uid']:'4';
        $list = db('study')->alias('s')
           ->field('a.*')
           ->join('articles a','s.articles_id = a.id')
           ->where("user_id = $user_id")
           ->select(); 
        return_function('200','',$list); 
    }
    /*微信登录*/
    public function wxLogin() {
         require_once '../vendor/program_login/WXBizDataCrypt.php';
         /*
         * 3.小程序调用server获取token接口, 传入code, rawData, signature, encryptData.
         */
        $code = input("code", '', 'htmlspecialchars_decode');
        $rawData = input("rawData", '', 'htmlspecialchars_decode');
        $signature = input("signature", '', 'htmlspecialchars_decode');
        $encryptedData = input("encryptedData", '', 'htmlspecialchars_decode');
        $iv = input("iv", '', 'htmlspecialchars_decode');

        /**
         * 4.server调用微信提供的jsoncode2session接口获取openid, session_key, 调用失败应给予客户端反馈
         * , 微信侧返回错误则可判断为恶意请求, 可以不返回. 微信文档链接
         * 这是一个 HTTP 接口，开发者服务器使用登录凭证 code 获取 session_key 和 openid。其中 session_key 是对用户数据进行加密签名的密钥。
         * 为了自身应用安全，session_key 不应该在网络上传输。
         * 接口地址："https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code"
         */
        $params = [
            'appid' => 'wxeb8d69f162b5120c',
            'secret' => '02bb9b8f11f077a1d9a897a23227b33f',
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        $res = _curl('https://api.weixin.qq.com/sns/jscode2session','GET',$params);
        $reqData = json_decode($res['result'], true);
        $sessionKey = $reqData['session_key'];
        $expiresIn = $reqData['expires_in'];
        $openId = $reqData['openid'];
        return_function('200','',['openid' => $openId]);
        // if ($res['code'] != 200 || !isset($res['result']) || !isset($res['result'])) {
        //     return json(ret_message('requestTokenFailed'));
        // }
        // $reqData = json_decode($res['result'], true);
        // if (!isset($reqData['session_key'])) {
        //     return json(ret_message('requestTokenFailed'));
        // }
        // $sessionKey = $reqData['session_key'];

        // /**
        //  * 5.server计算signature, 并与小程序传入的signature比较, 校验signature的合法性, 不匹配则返回signature不匹配的错误. 不匹配的场景可判断为恶意请求, 可以不返回.
        //  * 通过调用接口（如 wx.getUserInfo）获取敏感数据时，接口会同时返回 rawData、signature，其中 signature = sha1( rawData + session_key )
        //  *
        //  * 将 signature、rawData、以及用户登录态发送给开发者服务器，开发者在数据库中找到该用户对应的 session-key
        //  * ，使用相同的算法计算出签名 signature2 ，比对 signature 与 signature2 即可校验数据的可信度。
        //  */
        // $signature2 = sha1($rawData . $sessionKey);

        // if ($signature2 !== $signature) return ret_message("signNotMatch");

        // *
        //  *
        //  * 6.使用第4步返回的session_key解密encryptData, 将解得的信息与rawData中信息进行比较, 需要完全匹配,
        //  * 解得的信息中也包括openid, 也需要与第4步返回的openid匹配. 解密失败或不匹配应该返回客户相应错误.
        //  * （使用官方提供的方法即可）
         
        // $pc = new WXBizDataCrypt('wxf3da9e0d744569c5', $sessionKey);
        // $errCode = $pc->decryptData($encryptedData, $iv, $data );

        // if ($errCode !== 0) {
        //     return json(ret_message("encryptDataNotMatch"));
        // }


        // /**
        //  * 7.生成第三方3rd_session，用于第三方服务器和小程序之间做登录态校验。为了保证安全性，3rd_session应该满足：
        //  * a.长度足够长。建议有2^128种组合，即长度为16B
        //  * b.避免使用srand（当前时间）然后rand()的方法，而是采用操作系统提供的真正随机数机制，比如Linux下面读取/dev/urandom设备
        //  * c.设置一定有效时间，对于过期的3rd_session视为不合法
        //  *
        //  * 以 $session3rd 为key，sessionKey+openId为value，写入memcached
        //  */
        // $data = json_decode($data, true);
        // $session3rd = randomFromDev(16);

        // $data['session3rd'] = $session3rd;
        // cache($session3rd, $data['openId'] . $sessionKey);



        // return json($data);
    }
    public function login(){
        $param = input('param.');
        $openid = $param['openid'];
        $data = $member->getOnemember(['openid' => $openid]);
        $member = new MemberModel();
        if(empty($data)){
            $person_img = $param['person_img'];
            $person_name = $param['person_name'];
            $url = get_web_pic($person_img);
            $id = $member->addmember(['openid' => $openid,'person_img' => $url,'person_name' => $person_name]);
            $data = $member->getOnemember(['openid' => $openid]);
        }
        $data['person_img'] = $data['person_img']?APP_HTTP_HOST.$data['person_img']:'';
        return_function('200','',$data);
    }

}

